<template>
  <view class="countBox">
    {{ h }}:{{ m }}:{{ s }}
  </view>
</template>
<script>
export default {
  // time: '12:30',  notTimes: '10:48:07.911'
  props: {
    timer: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      d: '00',
      h: '00',
      m: '00',
      s: '00',
      difference: 0,
      timess: null,
      flag: false
    }
  },
  watch: {
    time (val) {
      this.startTime()
      this.flag = false
      this.timeUp()
    }
  },
  created () {
    this.startTime()
    this.timeUp()
  },
  methods: {
    // 初始化时间
    startTime () {
      let nowTime = new Date()
      this.difference = parseInt((nowTime.getTime() - this.timer) / 1000)
    },
    // 倒计时
    timeUp () {
      // 切换清除之前的定时器
      clearInterval(this.timess)
      this.timess = setInterval(() => {
        // console.log('遛宠中的定时器',this.s)
        if (this.flag === true) {
          clearInterval(this.timess)
        }
        this.difference = this.difference + 1
        if (this.difference > 0) {
          this.h = this.format(parseInt(this.difference / (60 * 60)))
          this.m = this.format(parseInt((this.difference / 60) % 60))
          this.s = this.format(parseInt(this.difference % 60))
          this.$emit('timeLen', `${this.h}:${this.m}:${this.s}`)
        } else {
          this.h = '00'
          this.m = '00'
          this.s = '00'
          this.flag = true
        }
      }, 1000)
    },
    // 时间格式
    format (time) {
      if (time >= 10) {
        return time
      } else {
        return `0${time}`
      }
    }
  }
}
</script>
<style lang="scss" >
.countBox {
}
</style>